package com.hdax.dm.controller;

import cn.hutool.http.HttpResponse;
import com.hdax.dm.feign.PayFeign;
import com.hdax.dm.order.DmOrder;
import com.hdax.dm.pay.DmTrade;
import com.hdax.dm.service.OrderService;
import com.hdax.dm.utils.response.CommonResponse;
import com.hdax.dm.utils.response.ResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(path = "/order/pay")
public class PayController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private PayFeign payFeign;

    @PostMapping(path = "/confirmpay")
    public CommonResponse<DmOrder> confirmpay(@RequestBody Map<String,String> map){
        List<DmOrder> orders = orderService.orderNos(map.get("orderNo"));
        DmOrder order = new DmOrder();
        for(DmOrder dm:orders){
            order = dm;
        }
        return ResponseUtils.returnSuccess(order);
    }

    @GetMapping(path = "/payMsg")
    public void changeOrder(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("支付宝订单号："+request.getParameter("trade_no"));
        System.out.println("商家订单号："+request.getParameter("out_trade_no"));
        System.out.println("买家支付宝id："+request.getParameter("buyer_id"));
        System.out.println("交易状态："+request.getParameter("trade_status"));
        System.out.println("实收金额："+request.getParameter("total_amount"));
        System.out.println("用户支付金额："+request.getParameter("buyer_pay_amount"));
        System.out.println("交易付款时间："+request.getParameter("gmt_payment"));
        String orderNo =request.getParameter("out_trade_no");
        String aliNo =request.getParameter("trade_no");
        String price = request.getParameter("total_amount");
        DmOrder order = new DmOrder();
        List<DmOrder> orders = orderService.orderNos(orderNo);
        orders.forEach(o->{
            order.setId(o.getId());
        });
        order.setAliTradeNo(aliNo);
        order.setOrderType(2L);
        order.setPayType("2");
        //支付成功修改订单支付宝账号状态
        Boolean b= orderService.updateById(order);
        //支付pay表添加内容
//        DmTrade trade = new DmTrade();
//        trade.setOrderNo(orderNo);
//        trade.setTradeNo(aliNo);
//        trade.setPayMethod(1L);
//        trade.setAmount(Double.valueOf(price));
//        trade.setCreatedTime(LocalDateTime.now());
//        Boolean pay = payFeign.save(trade);
//        System.out.println(pay);
        response.sendRedirect("http://localhost:8080/");
    }
}
